package handler

import (
	"essay/api/request"
	"essay/internal/dao"
	"essay/internal/models"
	"github.com/gin-gonic/gin"
)

func CreateComment(c *gin.Context) {
	var req request.CreateCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var comment models.Comment
	dao.GetOneByFields(&models.Comment{UserId: uint64(c.GetUint("userId"))}, &comment)
	var essay models.Essays
	dao.GetOneById(uint(req.EssayId), &essay)
	if essay.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "文章不存在",
			"data": nil,
		})
		return
	}
	m := models.Comment{
		UserId:  uint64(c.GetUint("userId")),
		EssayId: req.EssayId,
		Chat:    req.Chat,
	}
	if !dao.Create(&m) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "评论失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
		"data": m.Chat,
	})
}

func AnswerComment(c *gin.Context) {
	var req request.AnswerCommentReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var ans models.AnswerComment
	dao.GetOneByFields(&models.AnswerComment{
		UserId: uint64(c.GetUint("userId")),
	}, &ans)
	var comment models.Comment
	dao.GetOneById(uint(req.CommentId), &comment)
	if comment.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "评论不存在",
			"data": nil,
		})
		return
	}
	answerComment := models.AnswerComment{
		UserId:    uint64(c.GetUint("userId")),
		CommentId: req.CommentId,
		Chat:      req.Chat,
	}
	if !dao.Create(&answerComment) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "评论回复失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论回复成功",
		"data": answerComment.Chat,
	})
}
